<template>
  <div class="dashboard-container">
    <div class="app-container">
      <template>
        <el-row type="flex" justify="end" class="btn">
          <el-button type="primary" size="small" @click="addPerm('0','1')">添加权限</el-button>
        </el-row>
      </template>
      <el-table border :data="perList" row-key="id">
        <el-table-column label="名称" prop="title" />
        <el-table-column label="标识" prop="code" />
        <el-table-column label="描述" prop="description" />
        <el-table-column label="操作">
          <template v-slot="{row}">
            <el-button size="small" type="primary" @click="addPerm(row.id,'2')">添加子权限</el-button>
            <el-button size="small" @click="editFn(row.id)">编辑</el-button>
            <el-button size="small" type="danger" @click="delFn(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <addPermissions ref="addPerm" :show-dialog.sync="showDialog" @updateEvent="getPermissions" />
    </div>
  </div>
</template>

<script>
import addPermissions from './components/addpermission.vue'
import { delPermissions, getPermissions } from '@/api/permissions'
import { listToTree } from '@/utils/index'
export default {
  components: { addPermissions },
  data() {
    return {
      showDialog: false, // 弹窗
      perList: []// 权限列表
    }
  },
  created() {
    this.getPermissions()
  },
  methods: {

    // 渲染列表
    async getPermissions() {
      const res = await getPermissions()
      // console.log(res.data)
      this.perList = listToTree(res.data, '0')
    },
    // 新增权限
    addPerm(pid, type) {
      this.showDialog = true
      this.$refs.addPerm.formData.pid = String(pid)
      this.$refs.addPerm.formData.type = type
    },
    // 删除权限
    delFn(id) {
      this.$confirm('确定删除吗?', '提示', {
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(async() => {
        // 调用接口
        await delPermissions(id)
        // 刷新渲染
        this.getPermissions()
      }).catch(() => {
        console.log('点击了取消按钮')
      })
    },
    // 编辑权限
    editFn(id) {
      this.showDialog = true
      this.$refs.addPerm.getPermission(id)
    }
  }
}
</script>

<style scoped>
.app-container{
 box-shadow: 0px 0px 20px 2px rgb(0 0 0 / 20%);
    margin: 20px;
    border-radius: 5px;
}
.btn{
    margin-bottom: 10px;
}

</style>
